package com.example.emos.wx.user.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.extra.pinyin.PinyinUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.emos.wx.checkin.db.dao.TbCheckinDao;
import com.example.emos.wx.checkin.db.dao.TbFaceModelDao;
import com.example.emos.wx.checkin.model.form.CheckinForm;
import com.example.emos.wx.message.db.dao.MessageDao;
import com.example.emos.wx.message.db.dao.MessageRefDao;
import com.example.emos.wx.user.db.dao.TbDeptDao;
import com.example.emos.wx.user.db.dao.TbUserDao;
import com.example.emos.wx.user.model.pojo.TbUser;
import com.example.emos.wx.core.exception.EmosException;
import com.example.emos.wx.message.model.pojo.MessageEntity;
import com.example.emos.wx.message.task.MessageTask;
import com.example.emos.wx.user.service.UserService;
import com.example.emos.wx.user.task.ActiveCodeTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import java.util.*;


/**
 * 用户表业务层实现类
 *
 * @Author YinXi
 * @Versin 1.0.0
 * @Date 2023/8/4
 */
@Slf4j
@Service
//为了能够正常使用ThreadLocal中存储的内容实现多例的效果
@Scope("prototype")
public class UserServiceImpl implements UserService {
    @Value("${wx.app-id}")
    private String appId;
    @Value("${wx.app-secret}")
    private String appSecret;
    @Autowired
    private TbUserDao userDao;
    @Autowired
    private MessageTask messageTask;
    @Autowired
    private TbDeptDao deptDao;
    @Autowired
    private ActiveCodeTask activeCodeTask;
    @Autowired
    private TbCheckinDao checkinDao;
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private MessageRefDao messageRefDao;
    @Autowired
    private TbFaceModelDao faceModelDao;

    /**
     * 根据临时授权的code字符串获取OpenId
     *
     * @param code 临时授权的字符串
     * @return 获取到的OpenId字符串
     */
    private String getOpenId(String code) {
//        向微信平台发出请求的url地址
        String url = "https://api.weixin.qq.com/sns/jscode2session";
//        上传的必要若干参数
        HashMap map = new HashMap();
//        微信小程序的appid
        map.put("appid", appId);
//        微信小程序的app密钥
        map.put("secret", appSecret);
//        用户的临时授权码
        map.put("js_code", code);
//        固定的必填参数
        map.put("grant_type", "authorization_code");
//        使用Http工具向微信平台进行post请求获取响应
        String response = HttpUtil.post(url, map);
//        使用JSON工具将获得的响应内容转换为JSON格式提取其中的Openid
        JSONObject json = JSONUtil.parseObj(response);
        String openId = json.getStr("openid");
        if (openId == null || openId.length() == 0) {
            throw new RuntimeException("临时登录凭证错误");
        }
        return openId;
    }

    /**
     * 注册用户业务
     *
     * @param registerCode 激活码
     * @param code         临时授权字符串
     * @param nickname     昵称
     * @param photo        头像
     * @return
     */
    @Override
    public int registerUser(String registerCode, String code, String nickname, String photo) {
//        判断是不是超级管理员的激活码否则为普通用户注册
        if (registerCode.equals("000000")) {
//            查看是否已经存在超级管理员
            boolean isRoot = userDao.haveRootUser();
//            如果没有存在超级管理员
            if (!isRoot) {
//                获取OpenId
                String openId = getOpenId(code);
//                传入需要插入的数据到数据库
                HashMap param = new HashMap();
//                openId
                param.put("openId", openId);
//                微信昵称
                param.put("nickname", nickname);
//                微信头像
                param.put("photo", photo);
//                入职日期
                param.put("hiredate", DateUtil.format(new Date(),"yyyy-MM-dd"));
//                角色
                param.put("role", "[0]");
//                账号状态
                param.put("status", 1);
//                创建时间
                param.put("createTime", new Date());
//                是否为超级管理员
                param.put("root", true);
                userDao.insert(param);
//                返回插入的超级管理员的id
                int id = userDao.searchIdByOpenId(openId);
                MessageEntity entity = new MessageEntity();
                entity.setSenderId(0);
                entity.setSenderName("系统消息");
                entity.setUuid(IdUtil.simpleUUID());
                entity.setMsg("欢迎您注册成为超级管理员，请及时更新你的员工信息");
                entity.setSendTime(new Date());
                messageTask.sendAsync(id+"",entity);
                return id;
            } else {

                throw new EmosException("无法绑定超级管理员账号");
            }
        } else {
            return 1;
        }
    }

    /**
     * 获取用户对应的权限列表
     *
     * @param userId 用户ID
     * @return 权限列表集合
     */
    @Override
    public Set<String> searchUserPermissions(int userId) {
        Set<String> permissions = userDao.searchUserPermissions(userId);
        return permissions;
    }

    /**
     * 登录业务
     *
     * @param code 微信的临时授权字符串
     * @return 用户的id
     */
    @Override
    public Integer login(String code) {
//        根据临时授权字符串从微信平台获取对应的openId值
        String openId = getOpenId(code);
//        根据openid获取用户id
        Integer id = userDao.searchIdByOpenId(openId);
        if (id == null) {
            throw new EmosException("账户不存在");
        }
        return id;
    }

    /**
     * 根据id查询用户信息
     *
     * @param userId 用户id
     * @return 用户
     */
    @Override
    public TbUser searchById(int userId) {
        TbUser user = userDao.searchById(userId);
        return user;
    }

    /**
     * 查询用户的入职日期
     *
     * @param userId 用户id
     * @return 入职日期
     */
    @Override
    public String searchUserHiredate(int userId) {
        String hiredate = userDao.searchUserHiredate(userId);
        return hiredate;
    }

    @Override
    public HashMap searchUserSummary(int userId) {
        HashMap map = userDao.searchUserSummary(userId);
        return map;
    }

    @Override
    public ArrayList<HashMap> searchUserGroupByDept(String keyword) {
        ArrayList<HashMap> list_1 = deptDao.searchDeptMembers(keyword);
        ArrayList<HashMap> list_2 = userDao.searchUserGroupByDept(keyword);
        for (HashMap map_1 : list_1) {
            long deptId = (Long) map_1.get("id");
            ArrayList members = new ArrayList();
            for (HashMap map_2 : list_2) {
                long id = (Long) map_2.get("deptId");
                if(deptId == id){
                    members.add(map_2);
                }
            }
            map_1.put("members", members);
        }
        return list_1;
    }

    @Override
    public ArrayList<HashMap> searchMembers(List param) {
        ArrayList<HashMap> list = userDao.searchMembers(param);
        return list;
    }

    @Override
    public String searchMemberEmail(int id) {
        return userDao.searchMemberEmail(id);
    }

    @Override
    public List<HashMap> selectUserPhotoAndName(List param) {
        return userDao.selectUserPhotoAndName(param);
    }

    @Override
    public void insertUser(HashMap param) {
        int row = userDao.insert(param);
        if (row == 1) {
            String email = (String) param.get("email");
            int userId = userDao.searchUserIdByEmail(email);
            activeCodeTask.sendActiveCodeAsync(userId, email);
        } else {
            throw new EmosException("员工数据添加失败");
        }
    }

    @Override
    public HashMap searchUserInfo(Integer userId) {
        return userDao.searchUserInfo(userId);
    }

    @Override
    public int updateUserInfo(HashMap param) {
        int rows = userDao.updateUserInfo(param);
        if (rows == 1) {
            Integer userId = (Integer) param.get("userId");
            String msg = "你的个人资料已经被成功修改";
            MessageEntity entity = new MessageEntity();
            entity.setSenderId(0);
            entity.setSenderPhoto("../../static/system.jpg");
            entity.setSenderName("系统消息");
            entity.setMsg(msg);
            entity.setSendTime(new Date());

            messageTask.sendAsync(userId.toString(), entity);
        }

        return rows;
    }

    @Override
    public void deleteUserById(Integer id) {
        int row = userDao.deleteUserById(id);
        if (row != 1) {
            throw new EmosException("删除员工失败");
        }
        checkinDao.deleteUserCheckin(id);
        messageDao.deleteUserMessage(id);
        messageRefDao.deleteUserMessageRef(id);
        faceModelDao.deleteFaceModel(id);
        messageTask.deleteQueue(id + "");
    }

    @Override
    public JSONObject searchUserContactList() {
        ArrayList<HashMap> list = userDao.searchUserContactList();
        String letter = null;
        JSONObject json = new JSONObject(true);
        JSONArray array = null;
        for (HashMap<String, String> map : list) {
            String name = map.get("name");
            String firstLetter = PinyinUtil.getPinyin(name);
            firstLetter = firstLetter.toUpperCase();
            if (letter == null || !letter.equals(firstLetter)) {
                letter = firstLetter;
                array = new JSONArray();
                json.set(letter, array);
            }
            array.put(map);
        }
        return json;
    }
}
